import asyncio
import os

from sqlalchemy import text, select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from passlib.hash import bcrypt

from app.db import Base, _build_async_url
from app.models.user import User


async def init() -> None:
    url = _build_async_url(os.getenv("DB_URL", "sqlite+aiosqlite:///./dev.db"))
    engine = create_async_engine(url, future=True)

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async_session = async_sessionmaker(engine, expire_on_commit=False)
    async with async_session() as session:
        result = await session.execute(select(User).where(User.email == "admin@example.com"))
        existing = result.scalars().first()
        if not existing:
            user = User(
                email="admin@example.com",
                name="管理员",
                role="boss",
                password_hash=bcrypt.hash("admin"),
                active=True,
            )
            session.add(user)
            await session.commit()

    await engine.dispose()


if __name__ == "__main__":
    asyncio.run(init()) 